<template>
    <div id="publish">
        <cube-scroll>
            <!--S头部红包总额-->
            <div id="header" v-show="parseFloat(this.model.money) > 0  && parseInt(this.model.number) > 0">
                <div><p>红包总额</p><p>{{sum}}元</p></div>
                <div><p>手续费</p><p>{{charge}}元</p></div>
                <div><p>需支付</p><p>{{pay}}</p></div>
            </div>
            <!--E头部红包总额-->
            <div id="form">
                <cube-form
                        :model="model"
                        :schema="schema"
                        @submit.prevent = "submit"
                ></cube-form>
            </div>
        </cube-scroll>

        <shade :opacity="0" v-show="publishing"></shade>

        <!--S系统未开放发红包功能-->
        <div id="unable-publish" v-if="!parseInt(setting.publish_red) && !publish_person.includes(uid)">
            <div class="box">
                <div class="icon"></div>
                <h2>抱歉，您没用发红包的权限</h2>
                <cube-button @click="$router.go(-1)" class="close" :outline="true">关闭</cube-button>
            </div>
        </div>
        <!--E系统未开放发红包功能-->

        <!--S推广链接管理组件-->
        <i-link
                :toggle="show_link"
                :select="true"
                @close="show_link = false"
                @change="selectLinkId"
        >
        </i-link>
        <!--E推广链接管理组件-->

    </div>
</template>

<script>
    import Tool from '../../../util/Tool.js';
    import media from './components/media/Media';
    import question from './components/question/Question';
    import command from './components/command/Command';
    import areas from './components/area/Area';
    import link from './components/link/Link';
    import ilink from '../../../module/ilink/ILink';
    import shade from '../../../components/shade/Shade';
    import store from "../../../store/index";
    import {mapState} from "vuex";
    export default {
        name: "publish",
        data(){
            let self = this;
            return {
                uid:0,  // 当前用户uid
                show_link:false,  //是否显示推广链接管理组件
                red_id:0,  //红包id
                order_id:'',  //发红包支付订单号
                publishing:false,  //是否发布红包中
                type:"normal",  //红包类型
                ratio:0,  //服务费比例
                model:{
                    money:'',
                    type:'2',   //1=拼手气 2=普通红花
                    number:1,
                    cover:[],
                    title:'恭喜发财，大吉大利',
                    share:1,   //1=可分享传播  2=禁止传播
                    pic:[],  //图片红包图片列表
                    video:[],  //视频红包视频封面列表
                    video_value:[],  //视频红包视频列表
                    area_type:0,  //0=不限制开红包区域，1=限制省，2=限制市区，3=限制区/县
                    area:[],  //区域
                    open_check:0,   //开红包是否需要验证 0=不要验证问题 1=选择题，2=问答题
                    question:[],   //验证问题和答案选项
                    command_question:[],
                    link_id:"0"   //推广链接id
                },
                schema:{
                    fields: [
                        {
                            type:'input',
                            modelKey:'money',
                            label:'单个金额',
                            props:{
                                type:'text',
                                placeholder:'0.00'
                            },
                            rules:{
                                required:true,
                                type:'number',
                                pattern:/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
                            },
                            messages:{
                                required:'请输入红包金额',
                                type:'请输入正确的红包金额',
                                pattern:'请输入正确的红包金额'
                            }
                        },
                        {
                            type: 'radio-group',
                            modelKey: 'type',
                            label: '类型',
                            props:{
                                horizontal:true,
                                options:[
                                    {label:'普通',value:'2'},
                                    {label:'手气',value:'1'}
                                    ]
                            },
                            events:{
                                input:(value)=>{
                                    self.model.number = 1;
                                    if(value === '1'){
                                        self.schema.fields[0].label = '红包总额';
                                    }else{
                                        self.schema.fields[0].label = '单个金额';
                                    }
                                }
                            },
                            rules:{
                                required:true
                            }
                        },
                        {
                            type:'input',
                            modelKey:'number',
                            label:'红包个数',
                            props:{
                                type:'text',
                                placeholder:'填写个数'
                            },
                            rules:{
                                required:true,
                                type:'number',
                                max:1000000,
                                min:1,
                                pattern:/^\d+$/
                            },
                            messages:{
                                required:'请输入红包个数',
                                type:'请输入正确的红包个数',
                                max:'红包个数不能超过一百万',
                                min:'请输入正确的红包个数',
                                pattern:'请输入正确的红包个数'
                            }
                        },
                        {
                            type:'input',
                            modelKey:'title',
                            label:'标题',
                            props:{
                                type:'text',
                                placeholder:'红包标题'
                            },
                            rules:{
                                required:true,
                                max:10,
                                min:1
                            },
                            messages:{
                                required:'请输入红包标题',
                                max:'标题长度不能大于30',
                                min:'请输入红包标题'
                            }
                        },
                        {
                            type:media,
                            modelKey:'cover',
                            label:'红包封面',
                            props:{
                                number:1
                            },
                            events:{
                                remove(value){
                                    self.model.cover.splice(value,1);
                                },
                                change(value){
                                    self.model.cover.push(value);
                                }
                            },
                            rules:{
                                required:true
                            },
                            messages:{
                                required:'请设置红包封面'
                            }
                        },
                        {
                            type:'radio-group',
                            modelKey:'area_type',
                            label:'区域限制',
                            props: {
                                horizontal:true,
                                colNum:2,
                                options:[
                                    {
                                        label: '不限制',
                                        value: 0
                                    },
                                    {
                                        label: '省级',
                                        value: 1
                                    },
                                    {
                                        label:'市级',
                                        value:2
                                    },
                                    {
                                        label:'区(县)',
                                        value:3
                                    }
                                ]
                            },
                            rules:{
                                required:true
                            },
                            events:{
                                input(value){
                                    if(value === 0){
                                        for(let i=0;i<self.schema.fields.length;i++){
                                            if(self.schema.fields[i].modelKey === "area"){
                                                self.schema.fields.splice(i,1);
                                                break;
                                            }
                                        }
                                    }else{
                                        for(let i=0;i<self.schema.fields.length;i++){
                                            if(self.schema.fields[i].modelKey === "area"){
                                                self.schema.fields.splice(i,1);
                                                break;
                                            }
                                        }
                                        for(let i=0;i<self.schema.fields.length;i++){
                                            if(self.schema.fields[i].modelKey === "area_type"){
                                                let data = {
                                                        type:areas,
                                                        modelKey:'area',
                                                        label:"选择区域",
                                                        rules:{
                                                            required:true
                                                        },
                                                        props:{
                                                            level:value
                                                        }
                                                    };
                                                if(self.schema.fields[i+1].modelKey === "area"){
                                                    self.schema.fields.splice(i+1,1,data);
                                                }else{
                                                    self.schema.fields.splice(i+1,0,data);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        {
                            type:'radio-group',
                            modelKey:'share',
                            props: {
                                horizontal:true,
                                options:[
                                    {
                                        label: '公开红包',
                                        value: 1
                                    },
                                    {
                                        label: '仅邀请用户可领取',
                                        value: 0
                                    }
                                ]
                            }
                        },
                        {
                            type:link,
                            modelKey:'link_id',
                            label:'推广链接',
                            events:{
                                showLink(){
                                    self.show_link = true;
                                },
                                cancel(){
                                    self.model.link_id = '0'
                                    store.commit('setLinkName','')
                                }
                            }
                        },
                        {
                            type: 'submit',
                            label: '发红包',
                            props:{
                                primary:true
                            }
                        },
                        {
                            type: 'button',
                            label: '关闭',
                            events:{
                                click:()=>{
                                    this.$router.go(-1);
                                }
                            }
                        }
                    ]
                },
                pic_input:{  //红包图片选项
                    type:media,
                    modelKey:'pic',
                    label:'红包图片',
                    props:{
                        number:1
                    },
                    events:{
                        remove(value){
                            self.model.pic.splice(value,1);
                        },
                        change(value){
                            self.model.pic.push(value);
                        }
                    },
                    rules:{
                        required:true
                    },
                    messages:{
                        required:'请设置红包图片'
                    }
                },
                video_input:{  //红包视频选项
                    type:media,
                    modelKey:'video',
                    label:'红包视频',
                    props:{
                        number:1,
                        type:"video",
                    },
                    events:{
                        remove(value){
                            self.model.video.splice(value[0],1);
                        },
                        change(value){
                            self.model.video.push(value[0]);
                            self.model.video_value = value[1];
                        }
                    },
                    rules:{
                        required:true
                    },
                    messages:{
                        required:'请设置红包图片'
                    }
                },
                open_check:{
                    type: 'radio-group',
                    modelKey: 'open_check',
                    label: '答题领包',
                    props:{
                        horizontal:true,
                        colNum:2,
                        options:[
                            {label:'关闭',value:0},
                            {label:'选择题',value:1},
                            {label:'问答题',value:2}
                        ]
                    },
                    events:{
                        input:(value)=>{
                            let mode_key = this.schema.fields[7].modelKey;
                            if(mode_key === 'question' || mode_key=== 'command_question'){
                                this.schema.fields.splice(7,1);
                            }
                            if(value === 1){
                                this.schema.fields.splice(7,0,this.question_input);
                            }else if(value === 2){
                                this.schema.fields.splice(7,0,this.command_input);
                            }
                        }
                    },
                    rules:{
                        required:true
                    }
                },
                question_input:{
                    type:question,
                    modelKey:'question',
                    label:'答题内容',
                    rules:{
                        required:true
                    }
                },
                command_input:{
                    type:command,
                    modelKey:'command_question',
                    label:'答题内容',
                    rules:{
                        required:true
                    }
                }
            }
        },
        components:{
            shade,
            "i-link":ilink
        },
        computed:{
          //红包总额
          sum(){
              if(this.model.type === '2'){
                  //普通红包  总额=金额*红包数量
                  return (parseFloat(this.model.money) * parseInt(this.model.number)).toFixed(2);
              }else{
                  //手气红包  总额 = 金额;
                  return parseFloat(this.model.money).toFixed(2);
              }
          },
          //手续费
          charge(){
              return this.ratio == 0 ? 0 : Tool.toMoneyFormat((this.sum * this.ratio).toFixed(2));
          },
          //支付总额
          pay(){
              return Tool.toMoneyFormat(parseFloat(this.sum) + parseFloat(this.charge));
          },
          //手气红包，平均金额
          single_money(){
            if(this.model.type === '1'){
                return parseFloat(this.model.money) / parseInt(this.model.number);
            }else{
                return 0;
            }
          },
          ...mapState({
              setting:"setting",
              publish_person:"publish_person"
          })
        },
        watch:{
           single_money(data){
               if(this.model.type === '1' && data < 0.01){
                   this.$createToast({
                       time: 1500,
                       txt: '单个红包金额不能小于0.01元',
                       type:"error",
                       mask:true
                   }).show();
               }
           }
        },
        created(){
          this.type = this.$route.params.type;
          this.getPublishPerson();
          Tool.login()
            .then((res)=>{
                this.uid = res
            })
          if(this.type === 'pic'){
            this.schema.fields.splice(5,0,this.pic_input);
            this.schema.fields.splice(6,0,this.open_check);
          }else if(this.type === 'video'){
              this.schema.fields.splice(5,0,this.video_input);
              this.schema.fields.splice(6,0,this.open_check);
          }
          this.getRatio();
          //清空选择的推广链接内容
          store.commit("setLinkName","");
        },
        mounted() {
            let Input = document.querySelectorAll("#publish input");
            Input.forEach((item)=>{
                item.addEventListener("blur",()=>{
                    window.scroll(0,0);
                });
            });
            this.$nextTick(()=>{
                this.getAttentioQrcode();
            });
        },
        methods:{
            /**
             * 选择推广链接id触发事件
             */
            selectLinkId(value){
              this.model.link_id = value;
            },
            /**
             * 关注二维码显示
             */
            getAttentioQrcode(){
                Tool.getSetting()
                .then((setting)=>{
                    if(setting.attention_publish === '1'){
                        Tool.testAttention()
                            .then((res)=>{
                                if(res === '0'){
                                    Tool.getWxAttentionQrcode()
                                        .then((res)=>{
                                            this.$createDialog({
                                                type: 'alert',
                                                title:"长按关注不迷路",
                                                content:`<img src='${res}' style="width: 200px;" />`,
                                            }).show();
                                        });
                                }
                            });
                    }
                });
            },
            /**
             * 获取可开红包人员
             */
            getPublishPerson(){
                this.$url("personPublish/getPublishPerson")
                    .then((res)=>{
                        if(res.data.status === "success"){
                            let data = res.data.data;
                            let persons = [];
                            data.forEach((item)=>{
                                persons.push(parseInt(item.uid));
                            });
                            store.commit("setPublishPerson",persons);
                        }
                    });
            },
            /**
             * 服务费比率
             */
            getRatio(){
                this.$url('setting/easyFind',{
                    return:['normal_red_ratio','pic_red_ratio','video_red_ratio']
                })
                    .then((res)=>{
                        if(res.data.status == 'success'){
                            let data = res.data.data;
                            if(this.type === 'normal'){
                                this.ratio = parseFloat(data.normal_red_ratio);
                            }else if(this.type === 'pic'){
                                this.ratio = parseFloat(data.pic_red_ratio);
                            }else{
                                this.ratio = parseFloat(data.video_red_ratio);
                            }
                        }
                    });
            },
            /**
             * 提交
             */
            submit(){
                if(!this.submitCheck()) return false;
                this.publishing = true;
                let {money,type,number,title,cover,share,pic,video_value,open_check,question,command_question,area_type,area,link_id} = this.model;
                let data = {
                    money,
                    type,
                    number,
                    title,
                    cover:cover[0],
                    share,
                    open_check,
                    area_type,
                    area,
                    charge:this.charge,
                    pay:this.pay,
                    red_type:this.type,
                    link_id
                }
                if(this.type === 'pic'){
                    data.media = pic[0];
                }else if(this.type === 'video'){
                    data.media = video_value;
                }
                if(this.type !== 'normal'){
                    if(open_check === 1){
                        data.question = {
                            question: question[0],
                            answer:question[1],
                            options:[question[2],question[3],question[4]]
                        };
                    }else if(open_check === 2){
                        data.question = {
                            question:command_question[0],
                            answer:command_question[1]
                        };
                    }
                }
                this.$url('red/publish',{
                    data
                })
                    .then((res)=>{
                        if(res.data.status === "success"){
                            this.red_id = res.data.data;
                            this.publishPayParams();
                        }else{
                            this.$createToast({
                                time: 1500,
                                txt: '发红包失败',
                                type:'error',
                                mask:true
                            }).show();
                            this.publishing = false;
                        }
                    });
            },
            /**
             * 发红包验证
             */
            submitCheck(){
                if(this.model.type === '1' && this.single_money < 0.01){
                    this.$createToast({
                        time: 1500,
                        txt: '单个红包金额不能小于0.01元',
                        type:"error",
                        mask:true
                    }).show();
                    return false;
                }
                if(this.model.type === '1' && parseInt(this.model.number) <= 1){
                    this.$createToast({
                        time: 1500,
                        txt: '手气红包个数必须大于1',
                        type:"error",
                        mask:true
                    }).show();
                    return false;
                }
                //开红包选择题验证
                if(this.model.open_check === 1){
                    if(this.model.question[0].length < 2){
                        this.$createToast({
                            time: 1500,
                            txt: '请输入答题红包的题目',
                            type:"error",
                            mask:true
                        }).show();
                        return false;
                    }
                    if(this.model.question[2] === '' || this.model.question[3] === ''){
                        this.$createToast({
                            time: 1500,
                            txt: '最少设置两个答案供用户选择',
                            type:"error",
                            mask:true
                        }).show();
                        return false;
                    }
                }
                //开红包问答题验证
                if(this.model.open_check === 2){
                    if(this.model.command_question.length != 2 || this.model.command_question[0] === '' || this.model.command_question[1] === ''){
                        this.$createToast({
                            time: 1500,
                            txt: '请完善红包答题内容',
                            type:"error",
                            mask:true
                        }).show();
                        return false;
                    }
                }
                //发红包区域限制验证
                if(this.model.area_type !== 0){
                    if(this.model.area.length <= 0){
                        this.$createToast({
                            time: 1500,
                            txt: '请选择开红包限制区域',
                            type:"error",
                            mask:true
                        }).show();
                        return false;
                    }
                }
                return true;
            },
            /**
             * 获取微信支付参数
             */
            publishPayParams(){
                this.$url('red/publishPayParams',{
                    red_id:this.red_id
                })
                    .then((res)=>{
                        if(res.data.status == 'success'){
                            let data = res.data.data;
                            this.order_id = data.order_id;
                            if(process.env.NODE_ENV === 'development'){
                                this.paySuccess();
                            }else{
                                this.$wx.chooseWXPay({
                                    timestamp: data.timeStamp,
                                    nonceStr: data.nonceStr,
                                    package: data.package,
                                    signType: data.signType,
                                    paySign: data.paySign,
                                    success: ()=>{
                                        this.paySuccess();
                                    },
                                    fail:()=>{
                                        this.payError();
                                    },
                                    complete: (res)=>{
                                        if(res.errMsg === 'chooseWXPay:cancel'){
                                            this.publishing = false;
                                        }
                                    }
                                });
                            }
                        }else{
                            this.$createToast({
                                time: 1500,
                                txt: res.data.err_msg,
                                type:'error',
                                mask:true
                            }).show();
                        }
                    });
            },
            /**
             * 支付成功
             */
            paySuccess(){
                this.$url('red/publishPaySuccess',{
                    red_id:this.red_id,
                    order_id:this.order_id,
                    type:this.model.type,
                })
                    .then((res)=>{
                        if(res.data.status === 'success'){
                            store.state.share.red_id = parseInt(this.red_id)
                                this.$createToast({
                                time: 1500,
                                txt: '红包发布成功',
                                type:'correct',
                                mask:true,
                                $events: {
                                    timeout:()=>{
                                        this.$router.go(-1);
                                    }
                                }
                            }).show();
                        }else{
                            this.$createToast({
                                time: 1500,
                                txt: '红包发布失败',
                                type:'error',
                                mask:true
                            }).show();
                        }
                        this.publishing = false;
                    });
            },
            /**
             * 支付失败
             */
            payError(){
                this.$createToast({
                    time: 1500,
                    txt: '发红包失败',
                    type:'error',
                    mask:true,
                    $events: {
                        timeout:()=>{
                            this.$url('red/publishPayError',{
                                red_id:this.red_id
                            }).then(()=>{
                                this.publishing = false;
                            });
                        }
                    }
                }).show();
            }
        }
    }
</script>

<style scoped lang="less" src="./publish.less"></style>
